package controllers;

import models.Orders;

import org.codehaus.jackson.JsonNode;
import org.springframework.beans.factory.annotation.Autowired;
import play.cache.Cache;
import play.data.Form;
import play.mvc.*;
import services.*;
import views.html.orders.addOrders;
import views.html.orders.index;
import views.html.orders.edit;



import java.util.List;

/**
 * Created by MANHCUONG on 12/26/13.
 */

@org.springframework.stereotype.Controller
public class OrderController extends Controller {
    @Autowired
    private OrderService orderService;
    private String valueSearch;

    public Result index() {
        valueSearch = "";
        List<Orders> orderList = orderService.getAllOrders();
        return ok(index.render("List of Order", orderList, valueSearch));
//        return ok(indexOrder.render("List of Order", orderList, valueSearch));
    }

    private Result redirectUtil(String filter){
        if (!filter.equals(null) && !filter.equals("")){
            List<Orders> ordersList = orderService.getAllOrders();
            return ok(index.render("List of Order", ordersList, filter));
        }
        return redirect(routes.OrderController.index());
    }
    //get All Orders from Orders table
    public Result getAllOrders(){
        valueSearch="";
        List<Orders> list= orderService.getAllOrders();
        return ok(index.render("List of Orders", list,valueSearch));
    }

    public Result createOrder() {
        Form<Orders> f = new Form<Orders>(Orders.class);
        return ok(addOrders.render("Create Orders", f));
    }
    public Result addOrder(){
        Form<Orders> f = Form.form(Orders.class).bindFromRequest();
        if(f.hasErrors()){
            return badRequest(addOrders.render("List of Customer", f));
        } else {
            Orders order = f.get();
            orderService.insertOrders(order);
            return redirectUtil(valueSearch);
        }
    }

    public Result delOrder(int id) {
        orderService.deleteOrders(id);
        return redirectUtil(valueSearch);
    }
    public  Result editOrder(int id){
        Form<Orders> f = new Form<Orders>(Orders.class);
        Orders ord = orderService.getOrdersById(new Integer(id));
        Form<Orders> fNew= f.fill(ord);
        return ok(edit.render("Edit Orders", fNew));
    }
//
    public Result updateOrder(){
        Form<Orders> f = Form.form(Orders.class).bindFromRequest();
        if(f.hasErrors()){
            return badRequest(edit.render("Update fail", f));
        } else {
            Orders or = f.get();
            orderService.updateOrders(or);
            return redirectUtil(valueSearch);
        }
    }
}
